package com.module.TraceSource.dao;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;

import base.dao.GenericHibernateDao;
import base.util.Page;

import com.activityClient.util.PropertiesUtil;
import com.module.TraceSource.vo.TsEntEvent;
import com.module.TraceSource.vo.TsEntFlow;

public class TsEntFlowDao extends GenericHibernateDao<TsEntFlow,Long>{
	private static TsEntFlowDao dao;
	
	private TsEntFlowDao() {
		super();
	}
	public synchronized static TsEntFlowDao getInstance(){
		if(dao == null){
			dao = new TsEntFlowDao();
		}
		return dao;
	}
	/**
	 * 角色设备流程操作权限列表
	 * @param session
	 * @param orgid
	 * @return
	 */
	public List findEntFlowByOrgId(Session session, String orgid){
		
		String hql="";
		List<TsEntFlow> flowlist = null;
		hql="from TsEntFlow as obj where obj.status != 'D' and  obj.orgid='"+orgid+"'";
		Query query = session.createQuery(hql.toString());
		flowlist = query.list();
		
		for(TsEntFlow ee:flowlist){
			hql="from TsEntEvent as obj where obj.status !='D' and obj.flowid='"+ee.getId()+"'";
			Query query2 = session.createQuery(hql.toString());
			List<TsEntEvent> eventlist = query2.list();
			ee.setTsEntEvents(eventlist);
		
		}
		
		;
		return flowlist;
	}
	
	
	
	/**
	 * 分页列出流程列表
	 * @param session
	 * @param obj
	 * @param page
	 * @return
	 */
	public Page getList(Session session, TsEntFlow obj, Page page) {
		String hql1 = "from TsEntFlow as obj where obj.status !='D' ";
		String hql2 = "select count(*) from TsEntFlow as obj where obj.status !='D' ";
		if(StringUtils.isNotBlank(obj.getFlowName())){
            hql1=hql1 +  " and obj.flowName = '"+obj.getFlowName()+"'";
            hql2=hql2 +  " and obj.flowName = '"+obj.getFlowName()+"'";
        }
		
		if(StringUtils.isNotEmpty(obj.getOrgid())){
			hql1=hql1 +  " and obj.orgid = '"+obj.getOrgid()+"'";
            hql2=hql2 +  " and obj.orgid = '"+obj.getOrgid()+"'";
		}
		
		Query query = session.createQuery(hql1);
        query.setFirstResult(page.getStart()).setMaxResults(page.getLimit());
        page.setTotal((long) ((Long) session.createQuery(hql2)
                .uniqueResult()).intValue());
        page.setRows(query.list());
		return page;
	}
	
	
	public boolean isExistFlow(Session session,String name,String orgId,Long id){
		StringBuffer sql = new StringBuffer(" select count(*) from ts_ent_flow where c_orgid='");
		sql.append(orgId).append("' and c_status!='D' and c_flow_name='").append(name).append("'");
		if(id != null && id !=0){
			sql.append(" and i_id !=").append(id);
		}
		
		SQLQuery query=session.createSQLQuery(sql.toString());
		int n=((java.math.BigInteger)query.uniqueResult()).intValue();
		return n>0?true:false;
	}
}
